import {WeaTableNew} from 'comsMobx'
import * as API from '../../apis/standCustomReport';
import * as mobx from "mobx";
import toNumber from 'lodash/toNumber';
import round from 'lodash/round';
import {WeaLocaleProvider} from "ecCom";

const {TableStore} = WeaTableNew;
const {observable, action, computed} = mobx;
const getLabel = WeaLocaleProvider.getLabel;

export class StandardCustomReportTableStore extends TableStore {

    @observable customeSearchParams = {};
    @observable reportid = 0;
    sortFields = [];
    sumMainFields = [];
    sumfielddecimals = {};

    constructor(props) {
        super();
        this.tableColSet = this.tableColSet.bind(this);
        this.setReportFields = this.setReportFields.bind(this);
    }

    tableColSet(isInit = false, searchParams = {},isReset = false, reportid = '') {
        if (isInit) {
            this.customeSearchParams = {...this.customeSearchParams, ...searchParams};
            this.reportid = reportid;
        }
        const modeid = this.customeSearchParams.templateid;
        const {dataKey, colSetKeys} = this;
        const method = isInit ? '1' : '0';
        this.tableUpdate({loading: true});
        const colSetParams = {method, dataKey, reportid: this.reportid , modeid};
        if (!isInit && !isReset) colSetParams['systemIds'] = `${colSetKeys.toJS()}`;
        API.tableColSet(colSetParams).then(data => {
            if (data.status) {
                //显示定制列
                if (data.destdatas) {
                    const keys = [];
                    data.destdatas.forEach(d => {
                        keys.push(d.dataIndex);
                    });
                    const datas = [].concat(data.destdatas).concat(data.srcdatas).filter((d) => {
                        return !!d.title && d.customCol != "false";
                    });
                    const newDatas = [];
                    datas.map(d => newDatas.push({id: d.dataIndex, name: d.title, description: d.title}));
                    this.tableUpdate({
                        colSetKeys: keys,
                        colSetdatas: newDatas,
                        loading: false,
                    });
                } else {
                    this.setColSetVisible(false);
                    setTimeout(function () {
                        location.reload();
                    },300)
                }
            } else {
                message.error('接口错误，请重新提交');
            }
        });
        return this;
    }

    //合计计算
    tableUpdate(object, isPending) {
        super.tableUpdate(object, isPending);
        if (object.hasOwnProperty('stsAllData') && object.hasOwnProperty('datas')) {
            const columns = object['columns']||[];
            const stsAllData = object['stsAllData'] || {};
            const stsFields = [];
            for (const key in stsAllData) {
                if (key.indexOf('field') > -1) {
                    stsFields.push(key);
                }
            }

            //计算小计标题显示列
            let subTotalDataIndex = '';
            for (let i=0;i<columns.length;i++) {
                const dataIndex = columns[i].dataIndex;
                const display = columns[i].display;
                if (display && stsFields.indexOf(dataIndex) == -1) {
                    subTotalDataIndex = dataIndex;
                    break;
                }
            }

            const datas = object['datas'] || [];
            const stsDatas = [];
            const sortFields = this.sortFields || [];
            let rowstsData = {};
            rowstsData[subTotalDataIndex] = `${getLabel(507599,'小计')}：`;
            let rowSortFieldVal = "";
            let stsData = {};
            const totalRowStyle = {background: '#FFFAE6',color:'#FF9800'};
            //如果合计是主表字段则同一个requestid 只计算一次
            let sumMainRequestIds = [];
            datas.forEach((record, index) => {
                let currentRowSortFieldVal = '';
                let requestid = record['requestid'];
                sortFields.forEach((fieldKey) => {
                    let v = record[fieldKey];
                    currentRowSortFieldVal += v;
                });
                if (index == 0) rowSortFieldVal = currentRowSortFieldVal;
                //当上一行排序字段值和当前和排序字段值不相等时
                if (sortFields.length > 0 && rowSortFieldVal != currentRowSortFieldVal) {
                    stsDatas.push({data: rowstsData, index: index - 1, style: totalRowStyle});
                    rowstsData = {};
                    rowstsData[subTotalDataIndex] = `${getLabel(507599,'小计')}：`;
                    rowSortFieldVal = currentRowSortFieldVal;
                }

                stsFields.forEach((fieldKey) => {
                    if(!(this.sumMainFields.indexOf(fieldKey) > -1 && sumMainRequestIds.indexOf(requestid) > -1)) {
                        let v = rowstsData[fieldKey] || 0;
                        let v1 = toNumber(record[fieldKey]);
                        let v2 = stsData[fieldKey] || 0;
                        rowstsData[fieldKey] = v + v1;
                        stsData[fieldKey] = v1 + v2;
                    }
                });
                //最后一行
                if (sortFields.length > 0 && index == datas.length - 1) {
                    stsDatas.push({data: rowstsData, index, style: totalRowStyle});
                }
                sumMainRequestIds.push(requestid);
            });
            if(stsDatas.length > 0) {
                stsDatas.map((item,index) => {
                    let {data = {}} = item;
                    stsFields.map((fieldKey) => {
                        let v  = data[fieldKey]  || 0;
                        let decimal = this.sumfielddecimals[fieldKey];
                        data[fieldKey] = round(v,decimal);
                    })
                })
                this.stsDatas = stsDatas;
                this.stsData = undefined;
            } else {
                for(var key in stsData){
                    let decimal = this.sumfielddecimals[key];
                    stsData[key] = round(stsData[key],decimal);
                }
                this.stsData = stsData;
            }
            if(datas && datas.length == 0) {
                this.isSts = false;
            }
        }
    }

    setReportFields(fields = [],sumMainFields = [],sumfielddecimals = {}) {
        this.sortFields = fields;
        this.sumMainFields = sumMainFields;
        this.sumfielddecimals = sumfielddecimals;
    }
}